<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>轮播图管理 - 后台管理系统</title>
		<!-- 引入Element UI样式 -->
		<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
		<!-- 引入Font Awesome -->
		<link rel="stylesheet"
			href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
		<!-- 引入Vue -->
		<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
		<!-- 引入Element UI组件库 -->
		<script src="https://unpkg.com/element-ui/lib/index.js"></script>
		<!-- 引入Axios -->
		<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
		<script src="../js/authChecker.js"></script>
		<style>
			/* 保持原有样式不变 */
			body {
				margin: 0;
				padding: 0;
				background-color: #f5f7fa;
				font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
			}

			.container {
				padding: 20px;
				box-sizing: border-box;
			}

			.page-title {
				font-size: 18px;
				font-weight: 500;
				color: #1f2329;
				margin-bottom: 20px;
				padding-bottom: 10px;
				border-bottom: 1px solid #e4e7ed;
			}

			.toolbar {
				margin-bottom: 15px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				flex-wrap: wrap;
				gap: 10px;
			}

			.search-container {
				width: 300px;
				min-width: 200px;
			}

			.action-buttons {
				display: flex;
				gap: 10px;
			}

			.table-container {
				background-color: #fff;
				border-radius: 4px;
				box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
				overflow: hidden;
			}

			.pagination-container {
				margin-top: 15px;
				text-align: right;
			}

			.upload-tip {
				margin-top: 10px;
				color: #606266;
				font-size: 12px;
			}

			@media (max-width: 768px) {
				.toolbar {
					flex-direction: column;
					align-items: stretch;
				}

				.search-container {
					width: 100%;
				}

				.action-buttons {
					width: 100%;
					justify-content: flex-end;
				}

				.el-dialog {
					width: 90% !important;
				}
			}

			/* 统一按钮颜色 - 匹配左侧树形框粉色 #FF1493 */
			.add {
				background-color: #FF1493 !important;
				border-color: #FF1493 !important;
			}

			/* 操作按钮样式调整 - 使文字颜色与图标一致 */
			.edit-btn {
				color: #696969 !important;
				/* 编辑按钮文字颜色（与图标一致） */
				border: 0.5px solid black !important;
				/* 固定边框 */
				width: 50px;
			}

			.del-btn {
				color: #696969 !important;
				/* 删除按钮文字颜色（与图标一致） */
				border: 0.5px solid black !important;
				/* 固定边框 */
				width: 50px;
			}

			/* 移除悬停效果，保持边框不变 */
			.edit-btn:hover,
			.del-btn:hover {
				color: #696969 !important;
				border: 0.5px solid black !important;
				/* 保持边框不变 */
			}
		</style>
	</head>

	<body>
		<div id="app" class="container">
			<!-- 页面标题 -->
			<div class="page-title">轮播图管理</div>

			<!-- 操作工具栏 -->
			<div class="toolbar">
				<div class="search-container">
					<el-input placeholder="请输入轮播图标题搜索" v-model="searchKeyword" clearable prefix-icon="el-icon-search"
						@keyup.enter.native="handleSearch"></el-input>
				</div>

				<div class="action-buttons">
					<el-button class="add" type="primary" @click="handleAdd">
						<i class="fa fa-plus"></i> 新增轮播图
					</el-button>
				</div>
			</div>

			<!-- 轮播图列表 -->
			<div class="table-container">
				<el-table :data="carousels" border stripe style="width: 100%;" v-loading="loading">
					<el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>

					<el-table-column prop="title" label="标题" min-width="150"></el-table-column>

					<el-table-column prop="imageurl" label="图片预览" width="180" align="center">
						<template slot-scope="scope">
							<el-image :src="scope.row.imageurl" :preview-src-list="[scope.row.imageurl]"
								style="width: 100px; height: 60px; object-fit: cover;" lazy></el-image>
						</template>
					</el-table-column>

					<el-table-column prop="createtime" label="创建时间" width="180" align="center"></el-table-column>

					<el-table-column label="操作" width="180" align="center">
						<template slot-scope="scope">
							<el-button size="mini" type="text" @click="handleEdit(scope.row)" class="edit-btn">
								<i class="fa fa-pencil" style="color: #9c9c9c;"></i> 编辑
							</el-button>
							<el-button size="mini" type="text" @click="handleDelete(scope.row.id)" class="del-btn">
								<i class="fa fa-trash" style="color: #9c9c9c;"></i> 删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>

			<!-- 分页 -->
			<div class="pagination-container">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:current-page="currentPage" :page-sizes="[5]" :page-size="pageSize" :total="total"
					layout="total, sizes, prev, pager, next, jumper"></el-pagination>
			</div>

			<!-- 新增/编辑轮播图对话框 -->
			<el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%" :close-on-click-modal="false">
				<el-form :model="form" :rules="rules" ref="form" label-width="100px">
					<el-form-item label="轮播图标题" prop="title">
						<el-input v-model="form.title" placeholder="请输入轮播图标题"></el-input>
					</el-form-item>

					<el-form-item label="图片上传" prop="imageUrl">
						<el-upload :action="uploadUrl" :on-success="handleUploadSuccess" :on-error="handleUploadError"
							:before-upload="beforeUpload" :show-file-list="false" class="upload-demo">
							<el-image v-if="form.imageUrl" :src="form.imageUrl"
								style="width: 100%; height: 200px; object-fit: cover; cursor: pointer;"></el-image>
							<el-button v-else size="small" type="primary" style="width: 100%;">
								<i class="fa fa-upload"></i> 点击上传
							</el-button>
						</el-upload>
						<div class="upload-tip">支持JPG、PNG格式，建议尺寸1920×500px，大小不超过5MB</div>
					</el-form-item>

					<!-- 状态选择：单选按钮 -->
					<el-form-item label="状态">
						<el-radio-group v-model="form.status">
							<el-radio label="0">启用</el-radio>
							<el-radio label="1">禁用</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-form>

				<div slot="footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
				</div>
			</el-dialog>
		</div>

		<script>
			// 在页面加载时立即检查登录状态
			if (!checkAdminLogin()) {
				// 登录检查失败，阻止页面继续加载
				console.log('登录验证失败，已跳转至登录页');
			} else {
				new Vue({
					el: '#app',
					data() {
						return {
							searchKeyword: '',
							baseUrl: 'http://localhost:8887/carousel',
							currentPage: 1,
							pageSize: 10,
							total: 0,
							carousels: [],
							loading: false,
							dialogVisible: false,
							dialogTitle: '新增轮播图',
							form: {
								id: '',
								title: '',
								imageUrl: '',
								status: '0'
							},
							submitting: false,
							rules: {
								title: [{
										required: true,
										message: '请输入轮播图标题',
										trigger: 'blur'
									},
									{
										max: 50,
										message: '标题不能超过50个字符',
										trigger: 'blur'
									}
								]
							},
							uploadUrl: 'http://localhost:8887/upload/carouselImage',
						}
					},

					created() {
						this.fetchCarousels();
					},

					methods: {
						fetchCarousels() {
							this.loading = true;
							axios.get(`${this.baseUrl}/selectCarouselPageEnd`, {
									params: {
										page: this.currentPage,
										title: this.searchKeyword
									}
								})
								.then(response => {
									if (response.data.code !== 200) {
										this.$message.error(response.data.msgerr || '获取数据失败');
										return;
									}

									const formatDate = (dateStr) => {
										if (!dateStr) return '';
										const date = new Date(dateStr);
										return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
									};

									const list = response.data.data?.list || [];
									this.carousels = list.map(item => ({
										...item,
										createtime: formatDate(item.createtime)
									}));

									this.total = response.data.data?.total || 0;
								})
								.catch(error => {
									console.error('获取轮播图列表失败:', error);
									this.$message.error('获取数据失败，请刷新页面重试');
								})
								.finally(() => {
									this.loading = false;
								});
						},

						handleSearch() {
							this.currentPage = 1;
							this.fetchCarousels();
						},

						handleSizeChange(val) {
							this.pageSize = val;
							this.currentPage = 1;
							this.fetchCarousels();
						},

						handleCurrentChange(val) {
							this.currentPage = val;
							this.fetchCarousels();
						},

						handleAdd() {
							this.dialogTitle = '新增轮播图';
							this.form = {
								id: '',
								title: '',
								imageUrl: '',
								status: '0'
							};
							this.dialogVisible = true;
							this.$nextTick(() => {
								this.$refs.form && this.$refs.form.clearValidate();
							});
						},
						handleEdit(row) {
							console.log("row.status:", row.status);
							this.form = {
								id: row.id,
								title: row.title,
								imageUrl: row.imageurl,
								status: row.status != null ? row.status.toString() : '0'
							};
							this.dialogTitle = '编辑轮播图';
							this.dialogVisible = true;
						},
						handleDelete(id) {
							this.$confirm('确定要删除该轮播图吗?', '提示', {
								confirmButtonText: '确定',
								cancelButtonText: '取消',
								type: 'warning'
							}).then(() => {
								// 将 id 作为 URL 参数传递
								axios.post(`${this.baseUrl}/deleteCarouselIdEnd?id=${id}`)
									.then(response => {
										console.log("删除反应：");
										console.log(response);
										if (response.data.code === 200 || response.data === "删除成功") {
											this.$message.success('删除成功');
											this.fetchCarousels();
										} else {
											this.$message.error(response.data.msgerr || '删除失败');
										}
									})
									.catch(error => {
										console.error('删除错误:', error);
										this.$message.error('删除失败: ' + (error.response?.data?.msgerr || error
											.message));
									});
							});
						},
						handleSubmit() {
							this.$refs.form.validate((valid) => {
								if (valid) {
									this.submitting = true;

									// 关键修复：添加图片URL到表单数据
									const formData = new FormData();
									formData.append('title', this.form.title);
									formData.append('status', this.form.status);
									formData.append('imageUrl', this.form.imageUrl); // 新增这行，确保图片URL被提交
									if (this.form.id) {
										formData.append('id', this.form.id);
									}
									console.log("获取到的imageUrl:::" + this.form.imageUrl);

									axios.post("http://localhost:8887/upload/carouselHandle", formData)
										.then(response => {
											if (response.data.code === 200) {
												this.$message.success(this.form.id ? '编辑成功' : '新增成功');
												this.dialogVisible = false;
												this.fetchCarousels();
											} else {
												this.$message.error(response.data.msgerr || '操作失败');
											}
										})
										.catch(error => {
											console.error('提交错误:', error);
											this.$message.error('操作失败，请重试');
										})
										.finally(() => {
											this.submitting = false;
										});
								}
							});
						},

						// 重点优化：增强上传成功处理逻辑
						handleUploadSuccess(response) {
							console.log('上传响应:', response); // 用于调试


							if (response.code === 200) {
								this.form.imageUrl = response.data.url;
								this.$message.success(response.msgerr || '图片上传成功');
							} else {
								this.$message.error(response.msgerr || '图片上传失败');
							}
						},

						// 增强错误处理
						handleUploadError(error) {
							console.error('上传错误详情:', error);
							let errorMsg = '图片上传失败，请重试';

							// 提取更详细的错误信息
							if (error.response) {
								errorMsg = error.response.data?.msgerr ||
									`错误 ${error.response.status}: ${error.response.statusText}`;
							} else if (error.message) {
								errorMsg = error.message;
							}

							this.$message.error(errorMsg);
						},

						beforeUpload(file) {
							const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
							const isLt5M = file.size / 1024 / 1024 < 5;

							if (!isJPGOrPNG) {
								this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
								return false;
							}

							if (!isLt5M) {
								this.$message.error('上传图片大小不能超过 5MB!');
								return false;
							}

							return true;
						}
					}
				});
			}
		</script>
	</body>
</html>